/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.chigs.web.doku.module;

import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.target.basic.RedirectRequestTarget;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.StringValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import brix.BrixNodeModel;
import brix.web.nodepage.BrixNodeWebPage;
import brix.web.nodepage.BrixPageParameters;

import com.googlecode.chigs.domain.Module;
import com.googlecode.chigs.domain.Product;
import com.googlecode.chigs.domain.UserSettings;
import com.googlecode.chigs.web.ChigsApplication;
import com.googlecode.chigs.web.ChigsWebSession;
import com.googlecode.chigs.web.common.ModuleByProductDataProvider;
import com.googlecode.chigs.web.doku.revision.EditOrCreateRevisionPanel;
import com.googlecode.chigscommons.repository.GenericDomainService;
import com.googlecode.chigscommons.web.WicketWebSession;
import com.googlecode.chigscommons.web.common.ActionPanelBuilder;
import com.googlecode.chigscommons.web.common.DeleteActionLink;
import com.googlecode.chigscommons.web.common.EditActionLink;
import com.googlecode.chigscommons.web.common.HistoryActionLink;
import com.googlecode.chigscommons.web.common.IconFactory;
import com.googlecode.chigscommons.web.common.table.AjaxFallbackDefaultDataTableBuilder;

/**
 * 
 * @author Ingo Renner
 * @author Henning Teek
 *
 */
@AuthorizeInstantiation("ROLE_USER")
public class ManageModulesPanel extends Panel {
	private static final Logger log = LoggerFactory.getLogger(ManageModulesPanel.class);
	
	@SpringBean
	private GenericDomainService genericDomainService;

	private final Link<Void> createLink;
    private Product product;

	private final UserSettings userSettings;
	
	public ManageModulesPanel(String id, Long productId) {
		super(id);
		
		if (productId == null) {
			StringValue param = BrixPageParameters.getCurrent().getQueryParam("product");
			productId = !param.isEmpty() ? param.toLongObject() : null;
		}
		
		this.userSettings = ((ChigsWebSession) ChigsWebSession.get()).getUserSettings();
		this.product = productId != null ? genericDomainService.load(Product.class, productId) : userSettings.getProduct();

		createLink = new Link<Void>("create") {
			@Override
			public void onClick() {
				EditOrCreateRevisionPanel edit = new EditOrCreateRevisionPanel(ManageModulesPanel.this.getId(), product);
				edit.setOutputMarkupId(true);
				getPage().addOrReplace(edit);
				this.setVisible(false);
			}
		};
		createLink.add(new Image("icon", IconFactory.createAddBoxIconReference()));
		add(createLink.setVisible(this.product != null));
		add(getComponentTable());
		add(getProductSelector());
	}

	private DropDownChoice<Product> getProductSelector() {
		List<Product> products = genericDomainService.loadAll(Product.class);
		if (products.size() == 1){ // Selection nicht nötig
			ManageModulesPanel.this.product = products.get(0);
			getCreateLink().setVisible(true);
			ManageModulesPanel.this.addOrReplace(getComponentTable());
		}
		return new DropDownChoice<Product>("product",
				new PropertyModel<Product>(this, "product"),
				products,
				new ChoiceRenderer<Product>("name", "id")){
			@Override
			protected void onSelectionChanged(Product product) {
				log.info("changing product from " + product + " to " + ManageModulesPanel.this.product);
				ManageModulesPanel.this.product = product;
				userSettings.setProduct(product);
				genericDomainService.save(UserSettings.class, userSettings);
				getCreateLink().setVisible(true);
				ManageModulesPanel.this.addOrReplace(getComponentTable());
			}
			@Override
			protected boolean wantOnSelectionChangedNotifications() {
				return true;
			}
		};
	}

	private Component getComponentTable() {
		final String id = "table";
		if (product == null || product.isNew()) {
			return new Label(id, "").setVisible(false);
		}
		return AjaxFallbackDefaultDataTableBuilder.getBuilder(ManageModulesPanel.this)
		.addDataProvider(new ModuleByProductDataProvider(new Module(), product))
		.add(new AbstractColumn<Object>(new StringResourceModel("actions.label", ManageModulesPanel.this, null)) {
			@Override
			public void populateItem(Item cellItem, String componentId, IModel rowModel) {
				final ActionPanelBuilder linkBuilder = ActionPanelBuilder.getBuilder();
				final Module module = (Module) rowModel.getObject();
				// Eintrag editieren
				linkBuilder.add(new EditActionLink(false) {
					@Override
					public void onClick(AjaxRequestTarget target) {
						EditOrCreateRevisionPanel edit = new EditOrCreateRevisionPanel(ManageModulesPanel.this.getId(), product, module);
						edit.setOutputMarkupId(true);
						ManageModulesPanel.this.getParent().addOrReplace(edit);
					}
				});
				linkBuilder.add(new HistoryActionLink(false) {
					@Override
					public void onClick(AjaxRequestTarget target) {
						BrixPageParameters params = new BrixPageParameters();
						params.addQueryParam("product", product.getId().toString());
						params.addQueryParam("module", module.getId().toString());
						BrixNodeModel model = ((ChigsApplication) getApplication()).getI18nBrixLink(getSession(), "/documentation/revisions.html");
						getRequestCycle().setRequestTarget(new RedirectRequestTarget(params.urlFor(new BrixNodeWebPage(model))));
					}
				});
				// Delete darf nur ein Admin
				if (!((WicketWebSession) getSession()).getUser().isAdmin()) {
					DeleteActionLink removeLink = new DeleteActionLink(new StringResourceModel("actions.delete.confirm", ManageModulesPanel.this, null), false) {
						@Override
						public void onClick(AjaxRequestTarget target) {
							genericDomainService.delete(Module.class, module);
						}
					};
					linkBuilder.add(removeLink);
				}
				cellItem.add(linkBuilder.build(componentId));
			}
		})				
		.addPropertyColumn("id", true)
		.addPropertyColumn("name", true)
		.addPropertyColumn("latestRevision.nr", true)
		.addPropertyColumn("latestRevision.user.email", true)
		.addListProperty("latestRevision.dependencies", "name")
		.setNumberOfRows(10)
		.build(id);
	}

	public Link<Void> getCreateLink() {
		return createLink;
	}

}
